const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config')


// 用户登录处理函数
exports.login = (req, res) => {
    const userInfo = req.body
    const sql = 'select * from users where email = ?'
    db.query(sql, userInfo.email, (err, result) => {
        if(err) return res.show(err)
        if(result.length !== 1) return res.show("用户不存在！")
        // 用户存在 验证密码
        const compareResult = bcrypt.compareSync(userInfo.password, result[0].password)
        if(!compareResult) return res.show("请输入正确密码！")
        // 密码正确
        const user = { ...result[0], password: '', user_pic: '' }
        const token = jwt.sign( user, config.jwtSecretKey, { expiresIn: config.expiresIn })
        res.send({
            status: 0,
            message: "登录成功！",
            token: "Bearer " + token
        })
    })
}


// 用户注册处理函数
exports.register = (req, res) => {
    const userInfo = req.body
    // 查询是否已经注册
    const sql = 'select * from users where email = ?'
    db.query(sql, userInfo.email, (err, result) => {
        if(err) return res.show(err)
        if(result.length === 1) return res.show("用户账号已注册！")
        if(userInfo.password !== userInfo.resetpwd) return res.show("两次密码不一致！")
        // 对用户的密码进行 bcrypt.hashSync(明文密码, 随机盐的长度) 加密，返回加密密码
        userInfo.password = bcrypt.hashSync(userInfo.password, 10)
        const sql = 'insert into users set ?'
        db.query(sql, {email: userInfo.email, password: userInfo.password, username: userInfo.username}, (err, result) => {
            if(err) return res.show(err)
            if(result.affectedRows !== 1) return res.show("注册失败，请重试！")
            res.show("注册成功！", 0)
        })
    })
}

// 获取用户信息
exports.getUserInfo = (req, res) => {
    const sql = 'select userId, email, username, user_pic, signature from users where userId = ?'
    db.query(sql, req.user.userId, (err, result) => {
        if(err) return res.show(err)
        if(result.length !== 1) return res.show("获取用户信息失败！")
        // console.log(result[0])
        res.send({
            status: 0,
            message: "获取用户信息成功！",
            data: result[0]
        })
    })
}

// 更新用户信息
exports.updateUserInfo = (req, res) => {
    const sql = 'update users set ? where userId = ?'
    db.query(sql, [req.body, req.user.userId], (err, result) => {
        if(err) return res.show(err)
        if(result.affectedRows !== 1) return res.show("修改用户信息失败！")
        return res.show("修改用户信息成功！", 0)
    })
}

// 重置用户密码
exports.updatePassword = (req, res) => {
    const sql = 'select * from users where userId = ?'
    db.query(sql, req.user.userId, (err, result) => {
        if(err) return res.show(err)
        if(result.length !== 1) return res.show("用户不存在！")
        // 验证旧密码
        const compareResult = bcrypt.compareSync(req.body.oldPwd, result[0].password)
        if(!compareResult) return res.show("原密码错误！")
        // 加密新密码 更新数据库
        const sql = 'update users set password = ? where userId = ?'
        const newPwd = bcrypt.hashSync(req.body.newPwd, 10)
        db.query(sql, [newPwd, req.user.userId], (err, result) => {
            if(err) return res.show(err)
            if(result.affectedRows !== 1) return res.show("重置密码失败！")
            res.show("重置密码成功！", 0)
        })
    })
}

// 更新用户头像
exports.updateUserPic = (req, res) => {
    const sql = 'update users set user_pic = ? where userId = ?'
    db.query(sql, [req.body.user_pic, req.user.id], (err, result) => {
        if(err) return res.show(err)
        if(result.affectedRows !== 1) return res.show("更换头像失败！")
        return res.show("更换头像成功！", 0)
    })
}